package com.aaa.dao.impl;

import com.aaa.ann.ColumnAnn;
import com.aaa.ann.EntityAnn;
import com.aaa.dao.MyDao;
import com.aaa.entity.Dept;
import com.aaa.utils.BaseDao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/15 10:49
 * @description：我的通用dao实现类
 * @modified By：
 * @version: 1.0
 */
public class MyDaoImpl<T>  implements MyDao<T> {
    public void saveEntity(T obj) throws Exception {
        //1、通过获取class对象clazz
        Class<?> clazz = obj.getClass();
        //2、通过clazz获取一系列的注解值
        EntityAnn entityAnn = clazz.getAnnotation(EntityAnn.class);
        //获取表名  insert into tablename (colName1,colName2,) values ();
        String tableName = entityAnn.tableName();
        //获取列名
        Field[] fields = clazz.getDeclaredFields();
        //columnNames封装了所有的列名
        StringBuffer columnNames=new StringBuffer();
        //columnValues封装了所有的列值
        List<Object> columnValues= new ArrayList<Object>();
        for (Field field : fields) {
            //申请访问权限
            field.setAccessible(true);
            ColumnAnn columnAnn = field.getAnnotation(ColumnAnn.class);
            String colName = columnAnn.colName();
            //拼接所有的列名
            columnNames.append(colName).append(",");
            Object columnValue = field.get(obj);
            //封装了所有的列值
            columnValues.add("'"+columnValue+"'");
        }
        //去掉列名的最后一个逗号
        columnNames.deleteCharAt(columnNames.length()-1);
        //3、拼接sql语句
        StringBuffer sql=new StringBuffer("insert into ");
        sql.append(tableName).append("( ").append(columnNames);
        sql.append(" ) ").append("values (").append(columnValues).append(")");
        //4、执行sql语句
        String sqlFinal = sql.toString().replace("[", "").replace("]", "");
        Connection connection = BaseDao.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlFinal);
        preparedStatement.executeUpdate();
        preparedStatement.close();
        connection.close();
    }


    public static void main(String[] args) throws Exception {
        MyDao<Dept> deptMyDao= new MyDaoImpl<Dept>();
        Dept dept = new Dept();
        dept.setDeptno(91);
        dept.setDname("qy160");
        dept.setLoc("郑州");
        deptMyDao.saveEntity(dept);
    }
}
